import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/home/widgets/section.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/widgets/radio_button_group/index.dart";
import "package:fl_chart/fl_chart.dart";
import "package:flutter/material.dart";


class Overview extends StatefulWidget {
  final Map params;
  final Function? changeInfo;
  const Overview({super.key, required this.params, this.changeInfo});

  @override
  State<Overview> createState() => _OverviewState();
}

class _OverviewState extends State<Overview> with SingleTickerProviderStateMixin {
  String _currentTimeType = "month"; // 默认为月视图
  late TabController _tabController;
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(_handleTabChange);
  }
  
  @override
  void dispose() {
    _tabController.removeListener(_handleTabChange);
    _tabController.dispose();
    super.dispose();
  }

  /// 处理Tab切换
  void _handleTabChange() {
    if (_tabController.indexIsChanging) {
      setState(() {});
    }
  }

  /// 生成折线图的数据点
  List<FlSpot> _getSpots(List<Map<String, dynamic>> data) {
    return List.generate(data.length, (i) {
      return FlSpot(i.toDouble(), (data[i]['count'] ?? 0).toDouble());
    });
  }

  /// 生成用电量柱状图的数据
  List<BarChartGroupData> _getElectricityBarGroups(List<Map<String, dynamic>> data) {
    if (data.isEmpty) {
      return []; // 如果数据为空，返回空列表
    }
    
    // 根据数据点数量动态调整柱子宽度
    double barWidth = 12;
    if (data.length > 15) {
      barWidth = 8; // 数据点较多时，减小柱子宽度
    } else if (data.length > 30) {
      barWidth = 6; // 数据点非常多时，进一步减小柱子宽度
    }
    
    return List.generate(data.length, (i) {
      final usage = data[i]["usage"];
      final double usageValue = (usage is num) ? usage.toDouble() : 0.0;
      
      return BarChartGroupData(
        x: i,
        barRods: [
          BarChartRodData(
            toY: usageValue,
            color: ThemeVars.colorPrimary,
            width: barWidth,
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(4),
              topRight: Radius.circular(4),
            ),
            backDrawRodData: BackgroundBarChartRodData(
              show: true,
              toY: usageValue * 1.2, // 稍微高一点的背景
              color: ThemeVars.colorPrimary.withOpacity(0.1),
            ),
          ),
        ],
      );
    });
  }

  /// 根据入住率返回对应的颜色
  /// rate >= 80% 显示主色
  /// 60% <= rate < 80% 显示警告色
  /// rate < 60% 显示错误色
  Color _getOccupancyRateColor(num rate) {
    if (rate >= 80) return ThemeVars.colorPrimary;
    if (rate >= 60) return ThemeVars.colorWarning;
    return ThemeVars.colorError;
  }

  /// 处理时间类型变化
  void _handleTimeTypeChange(String type) {
    if (_currentTimeType != type) {
      setState(() {
        _currentTimeType = type;
      });
      
      // 根据选择的时间类型更新参数
      Map<String, dynamic> params = {
        "type": type,
      };
      
      // 根据不同的时间类型设置不同的时间范围
      DateTime now = DateTime.now();
      String endDate = DateTools.formatYMD(now, format: "{y}-{m}-{d} {h}:{i}:{s}");
      String startDate;
      
      switch (type) {
        case "year":
          // 最近6年
          startDate = DateTools.formatYMD(
            DateTime(now.year - 6, now.month, now.day, now.hour, now.minute, now.second),
            format: "{y}-{m}-{d} {h}:{i}:{s}"
          );
          break;
        case "month":
          // 最近12个月
          startDate = DateTools.formatYMD(
            DateTime(now.year, now.month - 12, now.day, now.hour, now.minute, now.second),
            format: "{y}-{m}-{d} {h}:{i}:{s}"
          );
          break;
        case "day":
          // 最近30天
          startDate = DateTools.formatYMD(
            now.subtract(const Duration(days: 30)),
            format: "{y}-{m}-{d} {h}:{i}:{s}"
          );
          break;
        case "hour":
          // 最近12小时
          startDate = DateTools.formatYMD(
            now.subtract(const Duration(hours: 12)),
            format: "{y}-{m}-{d} {h}:{i}:{s}"
          );
          break;
        default:
          // 默认最近30天
          startDate = DateTools.formatYMD(
            now.subtract(const Duration(days: 30)),
            format: "{y}-{m}-{d} {h}:{i}:{s}"
          );
      }
      
      params["startDate"] = startDate;
      params["endDate"] = endDate;
      
      // 通知父组件更新数据
      if (widget.changeInfo != null) {
        try {
          widget.changeInfo!(params);
        } catch (e) {
          print('Error updating electricity trend: $e');
        }
      }
    }
  }

  /// 根据时间类型格式化时间标签
  String _formatTimeLabel(String timeLabel, String timeType) {
    if (timeLabel.isEmpty) {
      return "";
    }
    
    try {
      switch (timeType) {
        case "year":
          // 尝试提取年份
          if (timeLabel.contains('-')) {
            final parts = timeLabel.split('-');
            if (parts.isNotEmpty) {
              return "${parts[0]}";
            }
          }
          return "$timeLabel";
          
        case "month":
          // 尝试提取月份
          if (timeLabel.contains('-')) {
            final parts = timeLabel.split('-');
            if (parts.length > 1) {
              return "${parts[1]}月";
            }
          }
          return "${timeLabel}月";
          
        case "day":
          // 尝试提取月-日
          if (timeLabel.contains('-')) {
            final parts = timeLabel.split('-');
            if (parts.length > 2) {
              return "${parts[1]}-${parts[2].split(' ')[0]}";
            } else if (parts.length > 1) {
              return "${parts[0]}-${parts[1].split(' ')[0]}";
            }
          }
          return timeLabel;
          
        case "hour":
          return "${timeLabel.split(' ')[1]}时";
          
        default:
          return timeLabel;
      }
    } catch (e) {
      print('Error formatting time label: $e');
      return timeLabel;
    }
  }

  /// 计算最佳显示间隔
  int _calculateInterval(int dataLength) {
    if (dataLength <= 5) return 1; // 数据点少于等于5个时，全部显示
    if (dataLength <= 10) return 2; // 数据点在6-10个时，每隔1个显示1个
    if (dataLength <= 20) return 4; // 数据点在11-20个时，每隔3个显示1个
    if (dataLength <= 30) return 6; // 数据点在21-30个时，每隔5个显示1个
    return (dataLength / 5).ceil(); // 数据点超过30个时，最多显示约5个标签
  }

  @override
  Widget build(BuildContext context) {
    // 获取并转换入住和退房趋势数据
    final List<Map<String, dynamic>> checkInTrend = 
        (widget.params['checkInTrend'] as List? ?? []).cast<Map<String, dynamic>>();
    final List<Map<String, dynamic>> checkOutTrend = 
        (widget.params['checkOutTrend'] as List? ?? []).cast<Map<String, dynamic>>();
    final List<Map<String, dynamic>> electricityTrend =
        (widget.params['data'] as List? ?? []).cast<Map<String, dynamic>>();
    
    return Section(
      title: "数据统计",
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: ThemeVars.colorBorder,
              offset: const Offset(0, 2),
              blurRadius: 8,
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Tab栏
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(12),
                  topRight: Radius.circular(12),
                ),
                border: Border(
                  bottom: BorderSide(
                    color: Colors.grey[100]!,
                    width: 1,
                  ),
                ),
              ),
              child: Row(
                children: [
                  _buildTabItem("入住统计", 0),
                  const SizedBox(width: 16),
                  _buildTabItem("用电统计", 1),
                ],
              ),
            ),
            // Tab内容
            SizedBox(
              height: 340, // 设置一个固定高度
              child: TabBarView(
                controller: _tabController,
                children: [
                  // 入住统计内容
                  Padding(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildTodayOverviewContent(checkInTrend, checkOutTrend),
                        const SizedBox(height: 16),
                        _buildTrendChartContent(checkInTrend, checkOutTrend),
                      ],
                    ),
                  ),
                  // 用电统计内容
                  Padding(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildElectricityOverviewContent(),
                        const SizedBox(height: 16),
                        _buildElectricityTrendChartContent(electricityTrend),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建小标题
  Widget _buildSubTitle(String title) {
    return Text(
      title,
      style: const TextStyle(
        fontSize: 14,
        fontWeight: FontWeight.w500,
        color: ThemeVars.colorTextSec,
      ),
    );
  }

  /// 构建今日概况内容
  Widget _buildTodayOverviewContent(
    List<Map<String, dynamic>> checkInTrend,
    List<Map<String, dynamic>> checkOutTrend,
  ) {
    // 获取今日数据（最后一个数据点）
    final todayCheckIn = checkInTrend.isNotEmpty ? 
        checkInTrend.last['count'] as num? ?? 0 : 0;
    final todayCheckOut = checkOutTrend.isNotEmpty ? 
        checkOutTrend.last['count'] as num? ?? 0 : 0;
    final rate = (widget.params['occupancyRate'] as num?) ?? 0;
    final color = _getOccupancyRateColor(rate);

    return Row(
      children: [
        Expanded(
          child: _buildOverviewItem(
            "入住率",
            "$rate%",
            color,
          ),
        ),
        Container(
          width: 1,
          height: 40,
          color: Colors.grey[100], // 使用更淡的分隔线颜色
        ),
        Expanded(
          child: _buildOverviewItem(
            "今日入住",
            "$todayCheckIn",
            ThemeVars.colorPrimary,
          ),
        ),
        Container(
          width: 1,
          height: 40,
          color: Colors.grey[100], // 使用更淡的分隔线颜色
        ),
        Expanded(
          child: _buildOverviewItem(
            "今日退房",
            "$todayCheckOut",
            ThemeVars.colorWarning,
          ),
        ),
      ],
    );
  }

  /// 构建近期用电数据内容
  Widget _buildElectricityOverviewContent() {

    String numToString(value) {
      return Utils.formatCurrency(Utils.toDouble(value));
    }

    return Column(
      children: [
        Row(
          children: [
            Expanded(
              child: _buildOverviewItem(
                "今日用电量",
                numToString(widget.params["todayUsage"]),
                ThemeVars.colorWarning,
              ),
            ),
            Container(
              width: 1,
              height: 40,
              color: Colors.grey[100], // 使用更淡的分隔线颜色
            ),
            Expanded(
              child: _buildOverviewItem(
                "本月用电量",
                numToString(widget.params["currentMonthUsage"]),
                ThemeVars.colorWarning,
              ),
            ),
            Container(
              width: 1,
              height: 40,
              color: Colors.grey[100], // 使用更淡的分隔线颜色
            ),
            Expanded(
              child: _buildOverviewItem(
                "今年用电量",
                numToString(widget.params["currentYearUsage"]),
                ThemeVars.colorWarning,
              ),
            ),
          ],
        ),
        SizedBox(height: 12,),
        Row(
          children: [
            Expanded(
              child: _buildOverviewItem(
                "昨日用电量",
                numToString(widget.params["yesterdayUsage"]),
                ThemeVars.colorPrimary,
              ),
            ),
            Container(
              width: 1,
              height: 40,
              color: Colors.grey[100], // 使用更淡的分隔线颜色
            ),
            Expanded(
              child: _buildOverviewItem(
                "上月用电量",
                numToString(widget.params["lastMonthUsage"]),
                ThemeVars.colorPrimary,
              ),
            ),
            Container(
              width: 1,
              height: 40,
              color: Colors.grey[100], // 使用更淡的分隔线颜色
            ),
            Expanded(
              child: _buildOverviewItem(
                "去年用电量",
                numToString(widget.params["lastYearUsage"]),
                ThemeVars.colorPrimary,
              ),
            ),
          ],
        )
      ],
    );
  }

  /// 构建趋势图内容
  Widget _buildTrendChartContent(
    List<Map<String, dynamic>> checkInTrend,
    List<Map<String, dynamic>> checkOutTrend,
  ) {
    // 获取日期标签
    final List<String> bottomTitles = checkInTrend.map((item) {
      final date = item['date'] as String? ?? '';
      final dateArr = date.split(' ')[0].split('-');
      return "${dateArr[1]}-${dateArr[2]}"; // 显示月-日
    }).toList();

    // 计算Y轴最大值
    final allCounts = [...checkInTrend, ...checkOutTrend]
        .map((item) => item['count'] as num? ?? 0)
        .toList();
    final maxCount = allCounts.isEmpty ? 5 : 
        (allCounts.reduce((max, value) => max > value ? max : value) + 1).toInt();

    // 计算显示间隔
    int interval = _calculateInterval(bottomTitles.length);

    return Column(
      children: [
        // 图例
        Align(
          alignment: Alignment.centerRight,
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildLegend("入住", ThemeVars.colorPrimary),
              const SizedBox(width: 20),
              _buildLegend("退房", ThemeVars.colorWarning),
            ],
          ),
        ),
        const SizedBox(height: 8),
        // 折线图
        SizedBox(
          height: 160, // 降低图表高度
          child: LineChart(
            LineChartData(
              minY: 0,
              maxY: maxCount.toDouble(),
              gridData: FlGridData(
                show: true,
                drawVerticalLine: false,
                horizontalInterval: 1,
                getDrawingHorizontalLine: (value) {
                  return FlLine(
                    color: Colors.grey[100], // 使用更淡的网格线颜色
                    strokeWidth: 1,
                  );
                },
              ),
              titlesData: FlTitlesData(
                leftTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: true,
                    interval: 1,
                    reservedSize: 28,
                    getTitlesWidget: (value, meta) {
                      return Text(
                        value.toInt().toString(),
                        style: const TextStyle(
                          color: ThemeVars.colorTextTer,
                          fontSize: 12,
                        ),
                      );
                    },
                  ),
                ),
                rightTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
                topTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
                bottomTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: true,
                    reservedSize: 30, // 增加底部标签的预留空间
                    interval: interval.toDouble(), // 设置显示间隔
                    getTitlesWidget: (value, meta) {
                      final int index = value.toInt();
                      if (index >= bottomTitles.length) return const Text('');
                      
                      // 始终显示第一个和最后一个数据点的标签，中间数据点根据间隔显示
                      final bool isFirstOrLast = index == 0 || index == bottomTitles.length - 1;
                      if (!isFirstOrLast && index % interval != 0) {
                        return const Text('');
                      }
                      
                      return Padding(
                        padding: const EdgeInsets.only(top: 8),
                        child: Text(
                          bottomTitles[index],
                          style: const TextStyle(
                            color: ThemeVars.colorTextTer,
                            fontSize: 12,
                          ),
                          textAlign: TextAlign.center,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      );
                    },
                  ),
                ),
              ),
              borderData: FlBorderData(show: false),
              lineBarsData: [
                LineChartBarData(
                  spots: _getSpots(checkInTrend),
                  isCurved: false,  // 关闭曲线
                  color: ThemeVars.colorPrimary,
                  barWidth: 2,
                  dotData: FlDotData(show: false),
                  belowBarData: BarAreaData(
                    show: true,
                    color: ThemeVars.colorPrimary.withOpacity(0.1),
                  ),
                ),
                LineChartBarData(
                  spots: _getSpots(checkOutTrend),
                  isCurved: false,  // 关闭曲线
                  color: ThemeVars.colorWarning,
                  barWidth: 2,
                  dotData: FlDotData(show: false),
                  belowBarData: BarAreaData(
                    show: true,
                    color: ThemeVars.colorWarning.withOpacity(0.1),
                  ),
                ),
              ],
              lineTouchData: LineTouchData(
                enabled: true,
                touchTooltipData: LineTouchTooltipData(
                  tooltipBgColor: Colors.white,
                  tooltipRoundedRadius: 4,
                  tooltipPadding: const EdgeInsets.all(8),
                  tooltipMargin: 8,
                  getTooltipItems: (List<LineBarSpot> touchedBarSpots) {
                    return touchedBarSpots.map((barSpot) {
                      final index = barSpot.x.toInt();
                      if (index >= bottomTitles.length) return null;
                      
                      final isInTrend = barSpot.barIndex == 0;
                      return LineTooltipItem(
                        '${bottomTitles[index]}\n',
                        const TextStyle(
                          color: ThemeVars.colorTextSec,
                          fontWeight: FontWeight.bold,
                          fontSize: 12,
                        ),
                        children: <TextSpan>[
                          TextSpan(
                            text: '${isInTrend ? "入住: " : "退房: "}${barSpot.y.toInt()}',
                            style: TextStyle(
                              color: isInTrend ? ThemeVars.colorPrimary : ThemeVars.colorWarning,
                              fontSize: 14,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      );
                    }).toList();
                  },
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建用电趋势图内容
  Widget _buildElectricityTrendChartContent(
    List<Map<String, dynamic>> electricityTrend,
  ) {
    // 检查数据是否为空
    if (electricityTrend.isEmpty) {
      return Column(
        children: [
          // 图例和单选按钮组
          Align(
            alignment: Alignment.centerRight,
            child: RadioButtonGroup(
              groupList: [
                {"label": "年", "value": "year"}, 
                {"label": "月", "value": "month"}, 
                {"label": "日", "value": "day"}, 
                {"label": "小时", "value": "hour"},
              ],
              defaultValue: _currentTimeType,
              onChange: _handleTimeTypeChange,
            ),
          ),
          const SizedBox(height: 16),
          // 无数据提示
          SizedBox(
            height: 120,
            child: Center(
              child: Text(
                "暂无数据",
                style: TextStyle(
                  color: ThemeVars.colorTextTer,
                  fontSize: 14,
                ),
              ),
            ),
          ),
        ],
      );
    }
    
    // 获取日期标签
    final List<String> bottomTitles = electricityTrend.map((item) {
      final timeLabel = item['timeLabel'] as String? ?? '';
      return _formatTimeLabel(timeLabel, _currentTimeType);
    }).toList();

    // 计算Y轴最大值
    final allCounts = electricityTrend
        .map((item) => item["usage"] as num? ?? 0)
        .toList();
    final maxCount = allCounts.isEmpty ? 5 :
        (allCounts.reduce((max, value) => max > value ? max : value) + 1).toInt();

    // 单选框按钮组数据
    final groupList = [
      {"label": "年", "value": "year"}, 
      {"label": "月", "value": "month"}, 
      {"label": "日", "value": "day"}, 
      {"label": "小时", "value": "hour"},
    ];

    // 计算显示间隔
    int interval = _calculateInterval(bottomTitles.length);

    return Column(
      children: [
        // 图例和单选按钮组
        Align(
          alignment: Alignment.centerRight,
          child: RadioButtonGroup(
            groupList: groupList,
            defaultValue: _currentTimeType,
            onChange: _handleTimeTypeChange,
          ),
        ),
        const SizedBox(height: 16),
        // 柱状图
        SizedBox(
          height: 120, // 降低图表高度
          child: BarChart(
            BarChartData(
              minY: 0,
              maxY: maxCount.toDouble(),
              gridData: FlGridData(
                show: true,
                drawVerticalLine: false,
                horizontalInterval: 1,
                getDrawingHorizontalLine: (value) {
                  return FlLine(
                    color: Colors.grey[100], // 使用更淡的网格线颜色
                    strokeWidth: 1,
                  );
                },
              ),
              titlesData: FlTitlesData(
                leftTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: true,
                    interval: 1,
                    reservedSize: 28,
                    getTitlesWidget: (value, meta) {
                      return Text(
                        value.toInt().toString(),
                        style: const TextStyle(
                          color: ThemeVars.colorTextTer,
                          fontSize: 12,
                        ),
                      );
                    },
                  ),
                ),
                rightTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
                topTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
                bottomTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: true,
                    reservedSize: 30, // 增加底部标签的预留空间
                    interval: interval.toDouble(), // 设置显示间隔
                    getTitlesWidget: (value, meta) {
                      final int index = value.toInt();
                      if (index >= bottomTitles.length) return const Text('');
                      
                      // 始终显示第一个和最后一个数据点的标签，中间数据点根据间隔显示
                      final bool isFirstOrLast = index == 0 || index == bottomTitles.length - 1;
                      if (!isFirstOrLast && index % interval != 0) {
                        return const Text('');
                      }
                      
                      return Padding(
                        padding: const EdgeInsets.only(top: 8),
                        child: Text(
                          bottomTitles[index],
                          style: const TextStyle(
                            color: ThemeVars.colorTextTer,
                            fontSize: 12,
                          ),
                          textAlign: TextAlign.center,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      );
                    },
                  ),
                ),
              ),
              borderData: FlBorderData(show: false),
              barGroups: _getElectricityBarGroups(electricityTrend),
              alignment: BarChartAlignment.spaceAround,
              groupsSpace: electricityTrend.length > 20 ? 4 : 12, // 根据数据点数量动态调整间距
              barTouchData: BarTouchData(
                enabled: true,
                touchTooltipData: BarTouchTooltipData(
                  tooltipBgColor: Colors.white,
                  tooltipPadding: const EdgeInsets.all(8),
                  tooltipMargin: 8,
                  tooltipRoundedRadius: 4,
                  fitInsideHorizontally: true, // 确保提示框在水平方向上适应屏幕
                  fitInsideVertically: true, // 确保提示框在垂直方向上适应屏幕
                  getTooltipItem: (group, groupIndex, rod, rodIndex) {
                    if (groupIndex >= bottomTitles.length) return null;
                    final String formattedValue = Utils.formatCurrency(rod.toY);
                    return BarTooltipItem(
                      '${bottomTitles[groupIndex]}\n',
                      const TextStyle(
                        color: ThemeVars.colorTextSec,
                        fontWeight: FontWeight.bold,
                        fontSize: 12,
                      ),
                      children: <TextSpan>[
                        TextSpan(
                          text: '用电量: $formattedValue',
                          style: TextStyle(
                            color: ThemeVars.colorPrimary,
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    );
                  },
                ),
                touchCallback: (FlTouchEvent event, BarTouchResponse? touchResponse) {
                  // 可以在这里添加触摸回调逻辑
                },
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建概况项
  Widget _buildOverviewItem(String label, String value, Color color) {
    return Column(
      children: [
        Text(
          value,
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.w600,
            color: color,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            color: ThemeVars.colorTextTer,
          ),
        ),
      ],
    );
  }

  /// 构建图例项
  Widget _buildLegend(String label, Color color) {
    return Row(
      children: [
        Container(
          width: 12,
          height: 4,
          decoration: BoxDecoration(
            color: color,
            borderRadius: BorderRadius.circular(2),
          ),
        ),
        const SizedBox(width: 4),
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            color: ThemeVars.colorTextTer,
          ),
        ),
      ],
    );
  }

  /// 构建Tab项
  Widget _buildTabItem(String label, int index) {
    final bool isSelected = _tabController.index == index;
    
    return GestureDetector(
      onTap: () {
        _tabController.animateTo(index);
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: isSelected ? ThemeVars.colorPrimary : Colors.grey[50],
          borderRadius: BorderRadius.circular(4),
          boxShadow: isSelected ? [
            BoxShadow(
              color: ThemeVars.colorPrimary.withOpacity(0.2),
              blurRadius: 4,
              offset: const Offset(0, 1),
            )
          ] : null,
        ),
        child: Text(
          label,
          style: TextStyle(
            fontSize: 13,
            fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
            color: isSelected ? Colors.white : ThemeVars.colorTextSec,
          ),
        ),
      ),
    );
  }
}
